package com.book.web;

import com.book.pojo.User;
import com.book.service.UserService;
import com.book.service.impl.UserServiceImpl;
import com.book.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegistServlet extends HttpServlet {
    UserService userService=new UserServiceImpl();//因为web层不能直接操作dao层，故需要一个userService
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取请求参数
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String email=req.getParameter("email");
        String code=req.getParameter("code");//验证码
        System.out.println(userService.existUsername("admin2"));
        //2.检查验证码是否正确
        if(code.equalsIgnoreCase("abcde")){
        //3检查用户名是否可用
            if (userService.existUsername(username)) {
                //不可用
                //要回显的信息放到Request域中
                req.setAttribute("msg","用户名已存在!");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                System.out.println("用户名【"+username+"】已存在！");
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);//不得已转发到/book中默认访问的index.jpg下
            }else {
                //可用
                userService.registUser(new User(null,username,password,email));//调用数据库保存数据
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);//注册成功页面
            }
        }else {
            //要回显的信息放到Request域中
            req.setAttribute("msg","验证码错误！");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            System.out.println("验证码错误，请求转发！");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);//回到注册页面
        }
    }
}
